// 四、手写实现MyPromise源码
// 要求：尽可能还原Promise中的每一个api,并通过注释的方式描述思路和原理
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfiled' // 成功
const REJECTED = 'rejected' // 失败

class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (error) {
            this.reject(error)
        }
    }

    status = PENDING // MyPromise 状态
    value = undefined // 成功后的值
    reason = undefined // 失败后的原因
    successCallback = [] // 成功回调
    failedCallback = [] // 失败回调

    resolve = (value) => {
        // 等待状态程序才能往下执行
        if (this.status !== PENDING) {
            return
        }
        this.status = FULFILLED
        this.value = value // 保存成功之后的值
            // 判断成功回调是否存在，如果存在则调用
            // this.successCallback & this.successCallback(value)
        while (this.successCallback.length) {
            this.successCallback.shift()()
        }
    }

    reject = (reason) => {
        // 如果不是等待状态阻止程序往下执行
        if (this.status !== PENDING) {
            return
        }
        this.status = REJECTED
        this.reason = reason // 保存失败的原因
            // 判断失败回调是否存在，如果存在则调用
            // this.failedCallback & this.failedCallback(reason)
        while (this.failedCallback.length) {
            this.failedCallback.shift()()
        }
    }

    then(successCallback, failedCallback) {
        successCallback = successCallback ? successCallback : (value) => value
        failedCallback = failedCallback ?
            failedCallback :
            (reason) => {
                throw reason
            }
        let promise2 = new MyPromise((resolve, reject) => {
            // 判断状态，执行对应的回调函数
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                            // 如果x的值是普通值，直接调用resolve
                            // 如果是promise对象，查看primose对象返回的结果，如果结果是成功的调用resolve，如果是失败的调用reject
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failedCallback(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            } else {
                // 等待
                // 将成功回调和失败回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
                this.failedCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failedCallback(this.reason)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
            }
        })
        return promise2
    }

    finally(callback) {
        return this.then(
            (value) => {
                return MyPromise.resolve(callback()).then(() => value)
            },
            (reason) => {
                return MyPromise.resolve(callback()).then(() => {
                    throw reason
                })
            }
        )
    } catch (failedCallback) {
        return this.then(undefined, failedCallback)
    }

    static all(array) {
        let result = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value
                index++
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(
                        (value) => {
                            addData(i, value)
                        },
                        (reason) => {
                            reject(reason)
                        }
                    )
                } else {
                    // 普通值
                    addData(i, array[i])
                }
            }
        })
    }

    static resolve(value) {
        if (value instanceof MyPromise) {
            return value
        }
        return new MyPromise((resolve) => {
            resolve(value)
        })
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
        return reject(
            new TypeError('Chaining cycle detected for promise #<Promise>')
        )
    }
    if (x instanceof MyPromise) {
        // x.then((value) => {resolve(value), (reason) => {reject(reason)}})
        // 简化代码
        x.then(resolve, reject)
    } else {
        // 普通值
        resolve(x)
    }
}

module.exports = MyPromise